#ifndef _THREAD_HPP__
#define _THREAD_HPP__

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <unistd.h>
#include<unordered_map>
#include<memory>
using namespace std;

namespace ThreadModule
{
   
    static int number = 1;
    enum class STATUS
    {
        NEW,
        START,
        STOP
    };
    class Thread
    {
        using func_t = function<void(std::string )>;
    private:
        static void *Routine(void *args)
        {
            Thread *p = static_cast<Thread *>(args);
            p->_func(p->Name());
            return (void*)0;
        }

    public:
        Thread(func_t func) : _func(func), _status(STATUS::NEW), _joinable(true)
        {
            _name = "Thread-" + to_string(number++);
            _pid = getpid();
        }
        bool Start()
        {
            if (_status != STATUS::START)
            {
                int n = pthread_create(&_tid, nullptr, Routine, this);
                if (!n)
                {
                    _status = STATUS::START;
                    return true;
                }
            }
            return false;
        }
        bool Stop()
        {
            if (_status == STATUS::START)
            {
                int n = pthread_cancel(_tid);
                if (!n)
                {
                    _status = STATUS::STOP;
                    cout << "终止成功" << endl;
                    return true;
                }
            }
            return false;
        }
        bool Join()
        {
            if (_joinable)
            {
                int n = pthread_join(_tid, nullptr);
                if (!n)
                {
                    _status = STATUS::STOP;
                    return true;
                }
            }
            return false;
        } // 让线程等待回收别的进程
        void Detach()
        {
            _joinable = false;
            pthread_detach(_tid);
        } // 让线程分离
        bool IsJoinable()
        {
            return _joinable;
        }
        ~Thread()
        {
        }
        string Name(){
            return _name;
        }
    private:
        string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable; // 默认不分离
        func_t _func;   // 未来线程要执行的方法
        STATUS _status;
    };
}

#endif
